package emysql

import (
	"context"

	"git.edaijia-inc.cn/edaijia/ego/elogger"
	"git.edaijia-inc.cn/edaijia/ego/etracer"

	"github.com/SkyAPM/go2sky"
	xormctx "xorm.io/xorm/contexts"
)

type EMysqlHook struct {
	Config *EMysqlConfig
}

type ctxSpanKey struct{}

var ctxSpanKeyInstance = ctxSpanKey{}

func NewEMysqlHook(config *EMysqlConfig) *EMysqlHook {
	return &EMysqlHook{config}
}

func (h *EMysqlHook) BeforeProcess(c *xormctx.ContextHook) (context.Context, error) {
	return c.Ctx, nil
}

func (h *EMysqlHook) AfterProcess(c *xormctx.ContextHook) error {
	if span := c.Ctx.Value(ctxSpanKeyInstance); span != nil {
		etracer.EMysqlSpanEnd(span.(go2sky.Span), c.SQL, c.Err)
	}
	if c != nil && h.Config != nil && h.Config.Verbose {
		elogger.Debug(c.SQL)
	}

	return nil
}
